package com.aduerr.v1shouyin.mvp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.ActiveEntity;
import com.aduerr.v1shouyin.entity.GetLeShuaActiveCode;
import com.aduerr.v1shouyin.entity.LoginAccountEntity;
import com.aduerr.v1shouyin.entity.UserEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.unioncard.BaseUnionActivity;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.AccountPopup;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.action.PosActivate;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;
import com.yeahka.shouyintong.sdk.excep.ActionIllegalException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseUnionActivity {

    public static final String TAG = "LoginActivity";
    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.password)
    TextView password;
    @BindView(R.id.et_acount)
    EditText et_acount;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.iv_checked)
    CheckBox ivChecked;
    @BindView(R.id.iv_checked_auto_login)
    CheckBox ivCheckedAutoLogin;
    @BindView(R.id.rl_checked_password)
    RelativeLayout rlCheckedPassword;
    @BindView(R.id.iv_login)
    TextView ivLogin;
    @BindView(R.id.tv_network_monitoring)
    TextView tvNetworkMonitoring;
    String log = "";
    private String guid;
    private Boolean autologin;
    private Boolean remberpassword;
    private SweetAlertDialog pDialog;
    private AccountPopup accountPop;
    private String SnCode = "";
    private SytApi sytApi;


    BroadcastReceiver broadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action, Constants.ACTION)) {
                try {
                    sytApi.handleAction(intent, baseResp -> {
                        if(baseResp.isSuccessful() && baseResp instanceof PosActivate.Resp) {
                            Hawk.put(Constants.IS_ACTIVE, true);
                            showToast(String.format("终端密钥下载成功"));
                            runOnUiThread(() -> updateActiveState());
                        } else if(!baseResp.isSuccessful() && baseResp instanceof PosActivate.Resp) {
                            showToast(String.format("终端密钥下载失败:%s" +
                                    "(%s)", baseResp.getMsg(), baseResp.getCode()));
                        }
                    });
                } catch(ActionIllegalException e) {
                    e.printStackTrace();
                }
            }
        }

    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initBase() {
        super.initBase();
        ButterKnife.bind(this);
        initUI1();
    }

    private void initUI1() {
        guid = Hawk.get("DeviceID");

        sytApi = SytFactory.createSytIml(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION);
        registerReceiver(broadcastReceive, intentFilter);


        SnCode = Build.SERIAL;
        LogUtils.i("SnCode:" + SnCode);
        autologin = (Boolean) SharedPreferencesUtils.getParam(LoginActivity.this,
                "autologin", false);
        remberpassword = (Boolean) SharedPreferencesUtils.getParam(LoginActivity.this,
                "remberpassword", false);
        pDialog = new SweetAlertDialog(LoginActivity.this,
                SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#005fee"));
        pDialog.setTitleText("让数据为你所用");
        pDialog.setCancelable(false);
        pDialog.show();
        isBind(guid);
//        CrashReport.testJavaCrash();
    }

    // 每次进入的时候检查商家是否被解绑
    public void isBind(String query) {
        new Thread() {
            public void run() {
                postnetforcheckedisbandguid(query);
            }
        }.start();
    }

    // 每次进入的时候检查商家是否被解绑
    private void postnetforcheckedisbandguid(String query) {
        String url =Constants.BASE_URL+"/api/PosDeviceVerify";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("deviceId", query).build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String stringjson = response.body().string();
//            Log.e("Guid", stringjson);  返回的数据  "1|已绑定"
            if(TextUtils.isEmpty(stringjson)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       ToastUtils.showToast(LoginActivity.this,"未查询到绑定信息");
                        if(pDialog != null) {
                            pDialog.dismiss();
                        }
                }});
               return;
            }
            String s1 = stringjson.substring(1, stringjson.length() - 1);// 去掉返回字符串两边的
            String[] str = s1.split("\\|");
            if(str[0].equals("1")) {
                runOnUiThread(() -> {
                    if(pDialog != null) {
                        pDialog.dismiss();
                    }

                    if(Hawk.get(Constants.IS_ACTIVE, false)) {
                        skipToLoginMethed();
                    } else {
                        getActiveLeshuaActiveCode();
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(pDialog != null) {
                            pDialog.dismiss();
                        }
                        ToastUtils.showToast(LoginActivity.this, "没有绑定guid,请先绑定guid");
                        startActivity(new Intent(LoginActivity.this,
                                BangGuidActivity.class));
                        finish();

                    }
                });
            }

        } catch(IOException e) {
            e.printStackTrace();
            runOnUiThread(() -> {
                if(pDialog != null) {
                    pDialog.dismiss();
                }
                Log.e(TAG, "run: " + e.getMessage());
                ToastUtils.showToast(LoginActivity.this, e.getMessage());
                if(e instanceof SocketTimeoutException) {
                    Toast.makeText(LoginActivity.this, "网络连接超时",
                            Toast.LENGTH_SHORT).show();
                } else if(e instanceof ConnectException) {
                    Toast.makeText(LoginActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                } else if(e instanceof UnknownHostException) {
                    // .checknet +
                    Toast.makeText(LoginActivity.this, "检查网络状态",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "检查网络状态",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void getActiveLeshuaActiveCode() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("sncode", SnCode);

        APIRetrofit.getAPIService().getActiveLeshuaActiveCode(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetLeShuaActiveCode>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog != null) {
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull GetLeShuaActiveCode entity) {
                        if(entity.getSuccess() == 1) {
                            downloadTMK(entity.getAuthCode());
                        } else {
                            //此处注意  小票优化时主分支没有 好奇怪
                            if(entity.getErrMsg().equals("该设备码已激活")) {
                                Hawk.put(Constants.IS_ACTIVE, true);
                            } else {
                                ToastUtils.showToast(LoginActivity.this, entity.getErrMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        ToastUtils.showToast(LoginActivity.this, "网络异常");
                    }

                    @Override
                    public void onComplete() {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                    }
                });
    }

    public void downloadTMK(String authorizationCode) {
        PosActivate.Req req = new PosActivate.Req();
        req.authorizeCode = authorizationCode;
        sytApi.sendReq(req);
    }

    private void updateActiveState() {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("sncode", SnCode);

        APIRetrofit.getAPIService().updateActiveState(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ActiveEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog != null) {
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull ActiveEntity entity) {
                        if(entity.getSuccess() == 1) {
                            skipToLoginMethed();
                        } else {
                            ToastUtils.showToast(LoginActivity.this, entity.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        ToastUtils.showToast(LoginActivity.this, "网络异常");
                    }

                    @Override
                    public void onComplete() {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                    }
                });
    }


    //绑定成功去查询是否勾选了自动登录和记住密码
    private void skipToLoginMethed() {
        //勾选状态初始化
        ivCheckedAutoLogin.setChecked(autologin);
        ivChecked.setChecked(remberpassword);
        if(autologin) {//选择了自动登录
            ivChecked.setChecked(true);
            ivCheckedAutoLogin.setChecked(true);
            String account =
                    (String) SharedPreferencesUtils.getParam(LoginActivity.this,
                            "account", "");
            String password =
                    (String) SharedPreferencesUtils.getParam(LoginActivity.this,
                            "password", "");
            et_acount.setText(account);
            et_password.setText(password);
            toLogin(account, password);
        } else {//没有选择自动登录
            ivChecked.setChecked(false);
            ivCheckedAutoLogin.setChecked(false);
            if(remberpassword) {//记录了密码
                ivCheckedAutoLogin.setChecked(false);
                ivChecked.setChecked(true);
                String account =
                        (String) SharedPreferencesUtils.getParam(LoginActivity.this,
                                "account", "");
                String password =
                        (String) SharedPreferencesUtils.getParam(LoginActivity.this,
                                "password", "");
                et_acount.setText(account);
                et_password.setText(password);
            }
        }
    }

    //登录
    private void toLogin(String account, String password) {
        if(TextUtils.isEmpty(account)) {
            ToastUtils.showToast(this, "账号不能为空");
            return;
        }
        if(TextUtils.isEmpty(password)) {
            ToastUtils.showToast(this, "密码不能为空");
            return;
        }
        postNetforLogin(account, password);
    }

    private void postNetforLogin(String account, String password_content) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("userName", "" + account);
        addParams.put("password", "" + password_content);
        addParams.put("logType", "0");
        APIRetrofit.getAPIService().Signout(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<UserEntity>() {
                    @Override
                    public void onNext(UserEntity userEntity) {
                        int success = userEntity.getSuccess();
                        if(success == 1) {
                            Hawk.put("userName", account);
                            Hawk.put("password", password_content);
                            Hawk.put("level", userEntity.getData().getLevel());

                            Hawk.put("opId", String.valueOf(userEntity.getData().getSiteuserid()));
                            Hawk.put("oPass", password_content);
                            Hawk.put("LogID",String.valueOf(userEntity.getData().getLogID()));

                            SharedPreferencesUtils.setParam(LoginActivity.this,
                                    "account", account);
                            SharedPreferencesUtils.setParam(LoginActivity.this,
                                    "password", password_content);

                            if(DatabaseManager.getInstance().queryCount(LoginAccountEntity.class) < 3) {
                                if((DatabaseManager.getInstance().getQueryByWhere(LoginAccountEntity.class, "account", new String[]{account})).size() == 0) {
                                    LoginAccountEntity accountEntity =
                                            new LoginAccountEntity();
                                    accountEntity.setAccount(account);
                                    if(ivChecked.isChecked()) {
                                        accountEntity.setPassword(password_content);
                                    }
                                    DatabaseManager.getInstance().insert(accountEntity);
                                }
                            } else {
                                if((DatabaseManager.getInstance().getQueryByWhere(LoginAccountEntity.class, "account", new String[]{account})).size() == 0) {
                                    DatabaseManager.getInstance().deleteFirst(LoginAccountEntity.class, "id");
                                    LoginAccountEntity accountEntity =
                                            new LoginAccountEntity();
                                    accountEntity.setAccount(account);
                                    if(ivChecked.isChecked()) {
                                        accountEntity.setPassword(password_content);
                                    }
                                    DatabaseManager.getInstance().insert(accountEntity);
                                }
                            }


                            //将数据存入数据库
                            saveDateToDateBase(userEntity);

//                            将别名上传上去
                            JPushInterface.setDebugMode(false);
                            JPushInterface.init(LoginActivity.this);
                            //将这个设备的别名推送到jpush服务器上
                            postAlis(LoginActivity.this,
                                    String.valueOf(userEntity.getData().getSiteuserid()));

                            Intent intent = new Intent(LoginActivity.this,
                                    HomePageActivity.class);
                            intent.putExtra("userEntity", userEntity);
                            startActivity(intent);
                            finish();
//                            togetmendainlist();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            ToastUtils.showToast(LoginActivity.this,
                                    userEntity.getErrMsg());
                            startActivity(new Intent(LoginActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else {
//                            ToastUtils.showToast(LoginActivity.this, userEntity
//                            .getErrMsg());
//                        startActivity(new Intent(LoginActivity.this, BangGuidActivity
//                        .class));
//                        finish();
                            ToastUtils.showToast(LoginActivity.this,
                                    userEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e);
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(LoginActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(LoginActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Log.e("onError:", "error:-----" + e.getMessage());//R
                            // .string.checknet +
                            Toast.makeText(LoginActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(LoginActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 上传极光的别名
     *
     * @param context 上下文对象
     * @param alisId  别名ID
     */
    private void postAlis(Context context, String alisId) {
        JPushInterface.setAlias(context, alisId, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                Log.d("alias", "set alias result is" + i);
            }
        });
    }

    private void saveDateToDateBase(UserEntity userEntity) {
        SimpleDateFormat NetNeedpram = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String sellbegintime = sdFormatter.format(curDate);
        String netneedpram = NetNeedpram.format(curDate);
        Hawk.put("sellbegintime", sellbegintime);//符串类型
        Hawk.put("netneedpram", netneedpram);//设置界面请求的参数
        Hawk.put("logintime", curDate);
        Hawk.put("sellername", userEntity.getData().getDisplayname());//收银员姓名
        Hawk.put("shopname", userEntity.getData().getShopname());
        Hawk.put("company", userEntity.getData().getCompany());
        Hawk.put("leval", userEntity.getData().getLevel());
        Hawk.put("accountname", userEntity.getData().getAccountName());
        Hawk.put("BankPermitInfo", userEntity.getData().getBankPermitInfo());
        Hawk.put("BankPermitAccount", userEntity.getData().getBankPermitAccount());
        Hawk.put("agentcompany", userEntity.getData().getAgentcompany());
        Hawk.put("phone", userEntity.getData().getPhone());
        Hawk.put("agenttel", userEntity.getData().getAgenttel());
        Hawk.put("shopid", userEntity.getData().getShopid());
        Hawk.put("siteuserid", userEntity.getData().getSiteuserid());
    }

    @OnClick({R.id.iv_checked, R.id.iv_checked_auto_login, R.id.rl_checked_password,
            R.id.iv_login, R.id.tv_network_monitoring, R.id.iv_more_account})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.iv_checked://记住密码

                if(ivChecked.isChecked()) {//勾选了
                    String account1 = et_acount.getText().toString().trim();
                    String password1 = et_password.getText().toString().trim();
                    if(TextUtils.isEmpty(account1)) {
                        ivChecked.setChecked(false);
                        ToastUtils.showToast(this, "账号不能为空");
                        return;
                    }
                    if(TextUtils.isEmpty(password1)) {
                        ivChecked.setChecked(false);
                        ToastUtils.showToast(this, "密码不能为空");
                        return;
                    }
                    SharedPreferencesUtils.setParam(LoginActivity.this, "remberpassword"
                            , true);
                    SharedPreferencesUtils.setParam(LoginActivity.this, "account",
                            account1);
                    SharedPreferencesUtils.setParam(LoginActivity.this, "password",
                            password1);

                } else {//没有勾选
                    SharedPreferencesUtils.remove(LoginActivity.this, "remberpassword");
                    SharedPreferencesUtils.remove(LoginActivity.this, "account");
                    SharedPreferencesUtils.remove(LoginActivity.this, "password");
                }

                break;
            case R.id.iv_checked_auto_login://自动登录
                if(ivCheckedAutoLogin.isChecked()) {//勾选了
                    String account = et_acount.getText().toString().trim();
                    String password = et_password.getText().toString().trim();
                    if(TextUtils.isEmpty(account)) {
                        ivCheckedAutoLogin.setChecked(false);
                        ToastUtils.showToast(this, "账号不能为空");
                        return;
                    }
                    if(TextUtils.isEmpty(password)) {
                        ivCheckedAutoLogin.setChecked(false);
                        ToastUtils.showToast(this, "密码不能为空");
                        return;
                    }
                    ivCheckedAutoLogin.setChecked(true);
                    ivChecked.setChecked(true);
                    SharedPreferencesUtils.setParam(LoginActivity.this, "autologin",
                            true);
                    SharedPreferencesUtils.setParam(LoginActivity.this, "account",
                            account);
                    SharedPreferencesUtils.setParam(LoginActivity.this, "password",
                            password);
                } else {//没有勾选
                    ivCheckedAutoLogin.setChecked(false);
                    ivChecked.setChecked(false);
                    SharedPreferencesUtils.remove(LoginActivity.this, "autologin");
                    SharedPreferencesUtils.remove(LoginActivity.this, "account");
                    SharedPreferencesUtils.remove(LoginActivity.this, "password");

                }

                break;
            case R.id.rl_checked_password:
                break;
            case R.id.iv_login:
                ckickButtonForLogin();
                break;
            case R.id.tv_network_monitoring:
                startActivity(new Intent(LoginActivity.this, NetworkActivity.class));
                break;
            case R.id.iv_more_account:
                if(DatabaseManager.getInstance().queryCount(LoginAccountEntity.class) == 0) {
                    ToastUtils.showToast(this, "请输入账号");
                    return;
                }
                accountPop = new AccountPopup(LoginActivity.this);
                accountPop.setOnItemClickListener(entity -> {
                    et_acount.setText(entity.getAccount());
                    et_password.setText(entity.getPassword());
                });
                accountPop.showAsDropDown(et_acount);
                break;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(accountPop != null && accountPop.isShowing()) {
            accountPop.dismiss();
        }
        return super.onTouchEvent(event);

    }

    //下方的按钮的点击
    private void ckickButtonForLogin() {
        String trim = et_acount.getText().toString().trim();
        String trim1 = et_password.getText().toString().trim();
        toLogin(trim, trim1);
    }

    @Override
    public void onBackPressed() {
        //屏蔽返回事件
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceive);
        } catch(Exception e) {
            e.printStackTrace();
        }
        if(pDialog != null) {//释放内存
            pDialog = null;
        }
        super.onDestroy();
    }
}

